package com.centit.framework.ip.util;


import com.centit.fileserver.client.DefaultFileClient;
import com.centit.fileserver.client.po.FileStoreInfo;
import com.centit.framework.appclient.AppSession;
import com.centit.framework.components.CodeRepositoryUtil;
import com.centit.framework.security.model.CentitUserDetails;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class FileUploadUtil {
    private static AppSession appSession;
    private static DefaultFileClient fileClient;
    private static String urlStr = CodeRepositoryUtil.getSysConfigValue("uploaderpath") + "/service/download/pfile/";
    /**
     * 返回多个文件
     *
     * @param request
     * @return
     * @date 2018-5-15
     */
    public static List<FileItem> fileUploadMore(HttpServletRequest request) {
        List<FileItem> items = new ArrayList<FileItem>();

        MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        MultipartHttpServletRequest multiRequest = resolver.resolveMultipart(request);
        Map<String, MultipartFile> map = multiRequest.getFileMap();
        File f = null;
        for (Map.Entry<String, MultipartFile> entry : map.entrySet()) {
            CommonsMultipartFile cMultipartFile = (CommonsMultipartFile) entry.getValue();
            FileItem fi = cMultipartFile.getFileItem();
            items.add(fi);
        }
        return items;
    }

    public static DefaultFileClient getFileClient() {
        appSession = new AppSession(CodeRepositoryUtil.getSysConfigValue("uploaderpath"));//配置文件文件服务器路径
        fileClient = new DefaultFileClient();
        fileClient.setAppSession(appSession);
        fileClient.setFileServerExportUrl(CodeRepositoryUtil.getSysConfigValue("uploaderpath"));
        return fileClient;
    }

    /**
     * @param request
     * @return
     * @author 皇甫壮
     * @date 2018-5-15
     * 返回单个文件
     */
    public static CommonsMultipartFile fileUploadOne(HttpServletRequest request) {
        MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        MultipartHttpServletRequest multiRequest = resolver.resolveMultipart(request);
        Map<String, MultipartFile> map = multiRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entry : map.entrySet()) {
            CommonsMultipartFile cMultipartFile = (CommonsMultipartFile) entry.getValue();
            return cMultipartFile;
        }
        return null;
    }

    public static File getFile(HttpServletRequest request, String usercode) {
        //获取前台上传的文件
        CommonsMultipartFile items = fileUploadOne(request);
        //设置路径
        String path = request.getSession().getServletContext().getRealPath("")
                + File.separator + "ofd" + File.separator + usercode + File.separator;
        File file = new File(path + items.getOriginalFilename());
        //转换成file，生成虚拟文件，成功之后，删除文件放在finally中
        try {
            FileUtils.copyInputStreamToFile(items.getInputStream(), file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    public static File getFile(InputStream stream, HttpServletRequest request, String fileId) {
        //设置路径
        String path = request.getSession().getServletContext().getRealPath("")
                + File.separator + "ofd" + File.separator;
        File file = null;
        try {
            fileClient = getFileClient();
            FileStoreInfo fileStoreInfo = fileClient.getFileStoreInfo(fileId);
            if(fileStoreInfo!=null){
                file = new File(path + fileId + "."+fileStoreInfo.getFileType());
            }
            //转换成file，生成虚拟文件，成功之后，删除文件放在finally中
            FileUtils.copyInputStreamToFile(stream, file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    /**
     * @param request
     * @return
     * @throws IOException
     */
    private static InputStream fetchInputStreamFromRequest(HttpServletRequest request) throws IOException {
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (!isMultipart)
            return request.getInputStream();

        MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        MultipartHttpServletRequest multiRequest = resolver.resolveMultipart(request);
//		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> map = multiRequest.getFileMap();

        for (Map.Entry<String, MultipartFile> entry : map.entrySet()) {

            CommonsMultipartFile cMultipartFile = (CommonsMultipartFile) entry.getValue();
            FileItem fi = cMultipartFile.getFileItem();
            if (!fi.isFormField()) {
                return fi.getInputStream();
            }
        }
        return null;
    }

    //创建文件夹--多层
    public static boolean CreateMultilayerFile(String dir) {
        try {
            File dirPath = new File(dir);
            if (!dirPath.exists()) {
                dirPath.mkdirs();
            }
        } catch (Exception e) {
            System.out.println("创建多层目录操作出错: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static InputStream getInputStreamFromFileServer(String fileId) {
        URL url = null;
        InputStream inputStream = null;
        try {
            url = new URL(urlStr + fileId);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置超时间为3秒
            conn.setConnectTimeout(3 * 1000);
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            //得到输入流
            inputStream = conn.getInputStream();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return inputStream;
    }
}
